import mysql.connector
import sys
import time  # 时间相关功能
import subprocess
import ast
from contextlib import closing

def exec_scripts():
    try:
        # 连接MySQL数据库
        with closing(mysql.connector.connect(
            host="192.168.195.169",
            port=3306,
            user="root",
            password="WENfei@635",
            database="aidesk"
        )) as conn:
            try:
                with closing(conn.cursor(dictionary=True)) as cursor:
                    # 查询并按id排序
                    query = "SELECT id, shellstring FROM busi_eventconfig WHERE `status`='00000' ORDER BY ctime DESC"
                    cursor.execute(query)
                    scripts = cursor.fetchall()

                    if not scripts:
                        print("没有找到任何shellscript记录")
                        return

                    print(f"找到 {len(scripts)} 条脚本记录，将按顺序执行")

                    # 执行每个脚本
                    for script in scripts:
                        try:
                            script_id = script['id']
                            # 获取原始脚本内容
                            raw_code = script['shellstring']
                            
                            if not raw_code or not raw_code.strip():
                                print(f"脚本ID: {script_id} 内容为空，跳过执行")
                                continue
                            
                            try:
                                # Split command into parts and execute safely
                                try:
                                    command_parts = raw_code.strip().split()
                                    result = subprocess.run(
                                        command_parts,
                                        check=True,
                                        text=True,
                                        capture_output=True,
                                        timeout=30  # Add timeout
                                    )
                                    time.sleep(2)
                                    print(f"脚本ID: {script_id} 执行成功. 输出:\n{result.stdout}")
                                except subprocess.TimeoutExpired:
                                    print(f"脚本ID: {script_id} 执行超时")
                                except subprocess.CalledProcessError as e:
                                    print(f"脚本ID: {script_id} 执行失败. 错误:\n{e.stderr}")
                            except Exception as e:
                                print(f"执行脚本ID: {script_id} 时出错: {type(e).__name__}: {str(e)}")
                                continue
                                
                        except Exception as e:
                            print(f"处理脚本ID: {script_id} 时发生意外错误: {type(e).__name__}: {str(e)}")
                            continue

                    # 更新所有已处理脚本的状态
                    try:
                        update_sql = "UPDATE busi_eventconfig SET `status` = '11111' WHERE `status` = '00000'"
                        cursor.execute(update_sql)
                        conn.commit()
                        print(f"成功更新 {cursor.rowcount} 条脚本状态")
                    except Exception as e:
                        print(f"更新脚本状态失败: {e}")
                        conn.rollback()

            except mysql.connector.Error as err:
                print(f"数据库操作错误: {err}")
                if conn:
                    conn.rollback()
            except Exception as e:
                print(f"程序运行出错: {e}")
                if conn:
                    conn.rollback()

    except Exception as e:
        print(f"数据库连接失败: {e}")

if __name__ == "__main__":
    exec_scripts()